#!/usr/bin/python # for editor

import os.path
import sys

TARGET_BUILD    = 'commons'
TARGET_INSTALL  = 'commons-install'

CPPPATH         = '#commons'
CONFIG_H        = os.path.join('#commons', 'sobjc-commons', 'config.h')
CONFIG_LOG      = os.path.join('#commons', 'sobjc-commons', 'config.log')

HEADERS         = 'limits.h stddef.h stdlib.h string.h unistd.h ctype.h'
TYPES           = Split('off_t ptrdiff_t volatile') + ['long long']
FUNCS           = 'atexit memset malloc realloc'

INCLUDES        = 'bool.h config.h port.h defines.h list.h str_list.h str_stream.h st.h memory.h type.h utils.h builtin_sels.h' 
SRCS            = 'str_stream.c st.c utils.c memory.c type.c builtin_sels.c'
LIB             = 'sobjc-commons'

inc_dir_commons = '$INCDIR/sobjc-commons'

Import('env lib_dir')
env = env.Clone(CPPPATH=CPPPATH)
for h in Split(INCLUDES):
    h = 'sobjc-commons/' + h
    env.Command('$INCDIR/%s' % h, h,
                [Copy('$TARGET', '$SOURCE'), Chmod('$TARGET', 0644)])
env.Alias(TARGET_INSTALL, inc_dir_commons)

def build(env):
    env.Clean(CONFIG_H, CONFIG_H)
    if env.is_targeted(TARGET_BUILD, TARGET_INSTALL):
        if not '-c' in sys.argv:
            Import('CONF')
            if not os.path.exists(CONFIG_H) or \
                    os.path.getmtime(CONF) > os.path.getmtime(CONFIG_H):
                env = create_config_h(env)
                if os.path.exists(CONFIG_H):
                    os.utime(CONFIG_H, None)
        build_srcs(env)

def create_config_h(env):
    conf = Configure(env)
    conf.config_h = CONFIG_H
    check_headers(conf)
    check_types(conf)
    check_funcs(conf)
    return conf.Finish()

def check_headers(conf):
    headers = Split(HEADERS)
    no_headers = []
    for header in headers:
        if not conf.CheckCHeader(header):
            no_headers.append(header)

def check_types(conf):
    for t in TYPES:
        conf.CheckType(t)

def check_funcs(conf):
    funcs = Split(FUNCS)
    no_funcs = []
    for func in funcs:
        if not conf.CheckFunc(func):
            no_funcs.append(func)

def build_srcs(env):
    if env['STATIC']:
        lib = env.Library(LIB, Split(SRCS))
    else:
        lib = env.SharedLibrary(LIB, Split(SRCS))
    target = os.path.join(lib_dir, str(lib[0]))
    env.Command(target, lib,
                [Copy('$TARGET', '$SOURCE'), Chmod('$TARGET', 0644)])
    env.Alias(TARGET_INSTALL, target)

if '-h' not in sys.argv:
  build(env)

